Load data

library(tidyverse)
library(plotly)
library(p8105.datasets)

Let’s get a small dataset of Airbnb’s in NYC:

data("nyc_airbnb")

nyc_airbnb =
  nyc_airbnb |>
  mutate(stars = review_scores_location / 2) |>
  select(borough = neighbourhood_group,
         neighbourhood, stars, price, room_type, lat, long) |>
  drop_na(stars) |>
  filter(
    borough == "Manhattan",
    room_type == "Entire home/apt",
    price %in% 100:500)

Interactive scatterplot

We can add the price and rating/stars by creating a string text_label and it will show up when you hover over the item.

  • backslash-n in the code means a line break
nyc_airbnb |>
  mutate(text_label = str_c("Price: $", price, "\nRating: ", stars)) |>
  plot_ly(x = ~lat, y = ~long, color = ~price, text = ~text_label,
          type = "scatter", mode = "markers", alpha = 0.8)

Interactive boxplot

nyc_airbnb |> 
  mutate(neighbourhood = fct_reorder(neighbourhood, price)) |> 
  plot_ly(y = ~price, color = ~neighbourhood, type = "box", colors = "viridis")

Interactive bar plot

nyc_airbnb |>
  count(neighbourhood) |>
  mutate(neighbourhood = fct_reorder(neighbourhood, n)) |>
  plot_ly(x = ~neighbourhood, y = ~n, color = ~neighbourhood, type = "bar", colors = "viridis")

ggplotly

This exists, but Prof. Goldsmith doesn’t recommend using it. The quality of the graphic is not as good and the interactivity is slower.

ggp_scatter =
  nyc_airbnb |>
  ggplot(aes(x = lat, y = long, color = price)) +
  geom_point(alpha = 0.5)

ggplotly(ggp_scatter)

Dashboard

You can start with a template or File –> New File –> R Markdown –> From Template –> Flex Dashboard.

My code for the dashboard is in the dashboard.Rmd file.